<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import _ from 'lodash'
import { Search, Minus, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useEnumStore } from "@/store/enumeration";
import { schemeSaveOrUpdatePost } from "@/api/equity";
import useInstance from "@/hooks/useInstance";
import { useComListData } from "@/store/list"
import BlackSelect from "@/components/customSon/blackSelect.vue";
const { listCollect } = useComListData()
const btnLoading = ref(false)
defineOptions({
    name: "addScheme",
});
const showModel = ref(1)
const {
    schemeType,
    discountsType,
    grantType,
    expiryPeriodType
} = useEnumStore();
const emit = defineEmits(["refresh"]);
const { global } = useInstance();
const dialogBasic = ref({
    title: "新建方案配置",
    visible: false,
    width: 700,
    height: 550,
    showFooter: true,
    marginTop: "10vh",
});
const ruleFormRef = ref<FormInstance>();
/* 
schemeType ：连续包月：1 签约：2
discountsType：连续包月：1 签约：2 首周：3
schemeConfigletailsType：立减金：1  停车券：2 虚拟会员：3
grantType：直接发送：1 用户领取：2
*/
let channelForm = reactive<any>({
    schemeCode: null, //方案编码
    schemeName: null, //方案名称
    schemeType: 1, //方案类型
    maxAnnualPayNum: 9999, //最大续期次数
    //  这个地方就是 如果是类型1 就给第一个对象 如果2 就给两个对象
    configRespList: [
        {
            discountsType: null,// 优惠类型
            annualStart: null,// 期数起
            annualEnd: null,// 期数止
            deductionMoney: null,// 扣费金额
            intervalPeriod: null,// 间隔期数
            periodUnit: 2,//  间隔期数单位
            packageCode: null,// 权益包配置编码
            extInfo: [
                {
                    key: null,
                    value: null
                }
            ],
        },
        {
            discountsType: null,// 优惠类型
            annualStart: null,// 期数起
            annualEnd: null,// 期数止
            deductionMoney: null,// 扣费金额
            intervalPeriod: null,// 间隔期数
            periodUnit: 2,//  间隔期数单位
            packageCode: null,// 权益包配置编码
            extInfo: [
                {
                    key: null,
                    value: null
                }
            ],
        },
    ],
});
const validatePass2 = (rule: any, value: any, callback: any) => {
    if (!channelForm.configRespList[0]?.annualStart) {
        callback(new Error('请输入期数起始值'))
    } else if (channelForm.configRespList[0]?.annualStart >= value) {
        callback(new Error("期数起始值需要小于期数结束值"))
    } else {
        callback()
    }
}
const validatePass3 = (rule: any, value: any, callback: any) => {
    if (!channelForm.configRespList[1]?.annualStart) {
        callback(new Error('请输入期数起始值'))
    } else if (channelForm.configRespList[1]?.annualStart >= value) {
        callback(new Error("期数起始值需要小于期数结束值"))
    } else {
        callback()
    }
}
const rules = reactive<FormRules>({
    schemeName: [
        {
            required: true,
            trigger: "blur",
            message: "请输入方案名称",
        },
    ],
    maxAnnualPayNum: [
        {
            required: true,
            trigger: "blur",
            message: "请输入最大续期次数",
        },
    ],
    schemeType: [
        {
            required: true,
            trigger: "blur",
            message: "请选择方案类型",
        },
    ],
    'configRespList.0.intervalPeriod': [
        {
            required: true,
            trigger: "blur",
            message: "请输入续约周期",
        },
    ],
    'configRespList.0.packageCode': [
        {
            required: true,
            trigger: "blur",
            message: "请选择权益包方案",
        },
    ],
    'configRespList.1.packageCode': [
        {
            required: true,
            trigger: "blur",
            message: "请选择权益包方案",
        },
    ],
    'configRespList.1.intervalPeriod': [
        {
            required: true,
            trigger: "blur",
            message: "请输入续约周期",
        },
    ],
    'configRespList.1.deductionMoney': [
        {
            required: true,
            trigger: "blur",
            message: "请输入扣费金额",
        },
    ],
    'configRespList.0.deductionMoney': [
        {
            required: true,
            trigger: "blur",
            message: "请输入扣费金额",
        },
    ],
    'configRespList.0.annualStart': [
        {
            required: true,
            trigger: "blur",
            message: "请输入起始值",
        }
    ],
    'configRespList.0.firstPeriodDay': [
        {
            required: true,
            trigger: "blur",
            message: "请输入首期天数",
        }
    ],
    'configRespList.1.annualStart': [
        {
            required: true,
            trigger: "blur",
            message: "请输入起始值",
        }
    ],
    'configRespList.1.annualEnd': [
        {
            required: true,
            trigger: "blur",
            message: "请输入结束值",
        },
        {
            validator: validatePass3,
            trigger: 'blur'
        }
    ],
    'configRespList.1.firstPeriodDay': [
        {
            required: true,
            trigger: "blur",
            message: "请输入首期天数",
        }
    ],
    'configRespList.0.annualEnd': [
        {
            required: true,
            trigger: "blur",
            message: "请输入结束值",
        },
        {
            validator: validatePass2,
            trigger: 'blur'
        }
    ]
});
//显示弹框
const show = async (type: string, row?: any) => {
    dialogBasic.value.visible = true;
    console.log(channelForm);

    if (type === "add") {
        dialogBasic.value.title = "新建方案配置";
        dialogBasic.value.height = 500;
        resetForm();
        showModel.value = 1

        const res = setAllKeysToNull(channelForm)
        Object.assign(channelForm, res);
        channelForm.configRespList[0].extInfo.length = 0
        channelForm.configRespList[1].extInfo.length = 0
        channelForm.configRespList[0].extInfo.push({
            key: null,
            value: null
        })
        channelForm.configRespList[1].extInfo.push({
            key: null,
            value: null
        })
        nextTick(() => {
            channelForm.schemeType = 1
            channelForm.maxAnnualPayNum = 9999
            channelForm.configRespList[0].periodUnit = 2
            channelForm.configRespList[1].periodUnit = 2
        })

    } else {
        console.log(row, channelForm);

        dialogBasic.value.height = 550;
        dialogBasic.value.title = "方案配置详情";
        Object.assign(channelForm, row);
        const arr = row.configRespList[0] ? JSON.parse(row.configRespList[0].extInfo) : {}
        console.log(arr);

        if (arr && Object.keys(arr).length > 0) {
            channelForm.configRespList[0].extInfo = []
            Object.keys(arr).forEach(item => {
                channelForm.configRespList[0].extInfo.push({
                    key: item,
                    value: arr[item]
                })
            })
        } else {
            channelForm.configRespList[0].extInfo = []
            channelForm.configRespList[0].extInfo = [
                {
                    key: null,
                    value: null
                }
            ]
        }
        if (row.schemeType == 2) {
            const arr1 = row.configRespList[1] ? JSON.parse(row.configRespList[1].extInfo) : {}
            if (arr1 && Object.keys(arr1).length > 0) {
                channelForm.configRespList[1].extInfo = []
                Object.keys(arr1).forEach(item => {
                    channelForm.configRespList[1].extInfo.push({
                        key: item,
                        value: arr1[item]
                    })
                })
            } else {
                channelForm.configRespList[1].extInfo = []
                channelForm.configRespList[1].extInfo = [
                    {
                        key: null,
                        value: null
                    }
                ]
            }
        }

    }
};
const setAllKeysToNull = (obj: any): any => {
    if (typeof obj !== 'object' || obj === null) {
        // 如果不是对象或已经是 null，则直接返回
        return obj;
    }

    if (Array.isArray(obj)) {
        // 如果是数组，则遍历每个元素
        return obj.map(item => setAllKeysToNull(item));
    }

    // 如果是普通对象，则遍历每个键值
    const newObj = {};
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const value = obj[key];

            if (typeof value === 'object' && value !== null) {
                // 如果是嵌套的对象，则递归处理
                // @ts-ignore
                newObj[key] = setAllKeysToNull(value);
            } else {
                // 否则设置为 null
                // @ts-ignore
                newObj[key] = null;
            }
        }
    }

    return newObj;
}
const onClose = async () => {
    dialogBasic.value.visible = false;
    if (channelForm.schemeType == 1 && channelForm.configRespList.length == 1) {
        channelForm.configRespList.push({
            discountsType: null,// 优惠类型
            annualStart: null,// 期数起
            annualEnd: null,// 期数止
            deductionMoney: null,// 扣费金额
            intervalPeriod: null,// 间隔期数
            periodUnit: 2,//  间隔期数单位
            packageCode: null,// 权益包配置编码
        })
    }
    console.log(channelForm);
    const res = await setAllKeysToNull(channelForm)
    Object.assign(channelForm, res);
    // 直接关闭



    nextTick(async () => {
        channelForm.schemeType = 1
        channelForm.configRespList[0].periodUnit = 2
        channelForm.configRespList[1].periodUnit = 2
    })
    showModel.value = 1
    ruleFormRef.value?.resetFields()
    ruleFormRef.value?.clearValidate()

    setTimeout(() => {
        btnLoading.value = false
    }, 500);
    console.log(channelForm);

};

/* 连续包月 */
const onConfirmSimple = async () => {
    await ruleFormRef.value?.validate(async (isOk) => {
        btnLoading.value = true
        if (isOk) {
            const arr: any = {}
            channelForm.configRespList[0].extInfo && channelForm.configRespList[0].extInfo.forEach((item: any) => {
                // 数据判断
                if (item.key) {
                    arr[item.key] = item.value
                }
            })

            const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr)
            channelForm.configRespList[0].extInfo = newArr
            channelForm.configRespList[0].discountsType = 1
            channelForm.configRespList.splice(1, 1);
            const res = await schemeSaveOrUpdatePost({ ...channelForm });
            if (res.code == 20000) {

                channelForm.configRespList.push({
                    discountsType: null,// 优惠类型
                    annualStart: null,// 期数起
                    annualEnd: null,// 期数止
                    deductionMoney: null,// 扣费金额
                    intervalPeriod: null,// 间隔期数
                    periodUnit: 2,//  间隔期数单位
                    packageCode: null,// 权益包配置编码
                })
                onClose();
                emit("refresh");
                ElMessage({
                    type: "success",
                    message: channelForm.id ? "方案配置编辑成功" : "方案配置新增成功",
                });
            } else {
                btnLoading.value = false

            }

        } else {
            btnLoading.value = false
            ElMessage({
                type: "error",
                message: channelForm.id
                    ? "方案配置编辑失败 请重试！"
                    : "方案配置新增失败 请重试！",
            });
        }
    });
};
/* 首期加 续期 */
const onConfirmComplex = async () => {
    await ruleFormRef.value?.validate(async (isOk) => {
        btnLoading.value = true

        if (isOk) {
            const arr: any = {}
            channelForm.configRespList[0].extInfo && channelForm.configRespList[0].extInfo.forEach((item: any) => {
                // 数据判断
                if (item.key) {
                    arr[item.key] = item.value
                }
            })

            const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr)
            channelForm.configRespList[0].extInfo = newArr
            const arr1: any = {}
            channelForm.configRespList[1].extInfo && channelForm.configRespList[1].extInfo.forEach((item: any) => {
                // 数据判断
                if (item.key) {
                    arr1[item.key] = item.value
                }
            })

            const newArr1 = Object.keys(arr1).length == 0 ? "{}" : JSON.stringify(arr1)
            channelForm.configRespList[1].extInfo = newArr1


            channelForm.configRespList[0].discountsType = 3
            channelForm.configRespList[1].discountsType = 2
            const res = await schemeSaveOrUpdatePost(channelForm);
            if (res.code == 20000) {

                onClose();
                ElMessage({
                    type: "success",
                    message: channelForm.id ? "方案配置编辑成功" : "方案配置新增成功",
                });
                emit("refresh");
            } else {
                btnLoading.value = false

            }

        } else {
            btnLoading.value = false

            ElMessage({
                type: "error",
                message: channelForm.id
                    ? "方案配置编辑失败 请重试！"
                    : "方案配置新增失败 请重试！",
            });
        }
    });
}

const resetForm = () => {
    ruleFormRef.value?.resetFields();
};
const removeDomain = (item: any, type: number) => {
    if (type == 1) {
        const index = channelForm.configRespList[0].extInfo.indexOf(item)
        if (index !== -1) {
            channelForm.configRespList[0].extInfo.splice(index, 1)
        }
    } else {
        const index = channelForm.configRespList[1].extInfo.indexOf(item)
        if (index !== -1) {
            channelForm.configRespList[1].extInfo.splice(index, 1)
        }
    }

}
const btnAdd = (type: number) => {
    if (type == 1) {
        channelForm.configRespList[0].extInfo.push({
            key: null,
            value: null,
        });
    } else {
        channelForm.configRespList[1].extInfo.push({
            key: null,
            value: null,
        });
    }
};
defineExpose({
    show,
});

const onConfirm = () => {
    console.log("onConfirm");
}
const onNext = async () => {
    await ruleFormRef.value?.validate(async (isOk) => {
        if (isOk) {
            showModel.value = 2
        }
    })
}
const schemeTypeChange = (val: any) => {
    showModel.value = 1
    if (val != 1) {
        // channelForm.configRespList[0].intervalPeriod = 0
        channelForm.configRespList[0].periodUnit = 2
        channelForm.configRespList[1].periodUnit = 2
    } else {
        channelForm.configRespList[0].periodUnit = 2
    }

}
</script>

<template>
    <SysDialogSlot :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :draggable="true"
        :margin-top="dialogBasic.marginTop" @on-close="onClose" destroy-on-close @on-confirm="onConfirm">
        <template v-slot:content>
            <div class="channel-form">
                <el-form ref="ruleFormRef" :model="channelForm" :rules="rules" label-width="130px" class="demo-ruleForm"
                    status-icon>
                    <!-- 三个面板 怎么玩 什么办法可以让数据一直保存呢 不用频繁的切换 -->
                    <el-form-item label="方案名称" prop="schemeName">
                        <normal-input v-model:model-value="channelForm.schemeName" maxlength="120" disabled
                            show-word-limit></normal-input>
                    </el-form-item>

                    <el-form-item label="选择优惠方案" prop="schemeType">
                        <el-radio-group v-model="channelForm.schemeType" @change="schemeTypeChange">
                            <el-radio v-for="(item, index) in schemeType" :label="item.value" :key="index"
                                :disabled="!!channelForm.id" :value="item.id"> </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="最大续期次数" prop="maxAnnualPayNum">
                        <el-input-number v-model.number="channelForm.maxAnnualPayNum" style="width: 100%;" clearable disabled
                            :min="0" :max="9999" placeholder="请输入最大续期次数" :controls="false" />
                    </el-form-item>
                    <!-- 头部 第一部分只是有没有 添加的东西-->

                    <template v-if="showModel == 1">
                        <el-divider content-position="left" v-if="channelForm.schemeType == 1">基础（连续包月）</el-divider>
                        <el-divider content-position="left" v-else>支付（首期优惠）和 签约（续约优惠）</el-divider>
                        <!-- 1 -->
                        <div v-if="channelForm.schemeType == '1'">
                            <el-row>
                                <el-col :span="10">
                                    <el-form-item prop="configRespList.0.annualStart" label="输入期数">
                                        <el-input-number v-model.number="channelForm.configRespList[0].annualStart" disabled
                                            clearable :min="0" :max="9998" placeholder="起始值 0-9998" :controls="false" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">

                                    <el-form-item prop="configRespList.0.annualEnd" label-width="10px">
                                        <el-input-number v-model.number="channelForm.configRespList[0].annualEnd" disabled
                                            clearable :min="1" :max="9999" placeholder="结束值 1-9999" :controls="false" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="期数间隔" prop="configRespList.0.intervalPeriod">
                                    <el-input-number v-model.number="channelForm.configRespList[0].intervalPeriod" disabled
                                        clearable :min="1" :max="127" placeholder="期数间隔" :controls="false" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label-width="10px">
                                    <BlackSelect v-model:select-value="channelForm.configRespList[0].periodUnit"
                                        style="width: 150px;" disabled :options="expiryPeriodType"></BlackSelect>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <!-- 2 -->
                        <el-form-item label="扣费金额" prop="configRespList.0.deductionMoney">
                            <el-input-number :precision="2" style="width: 145px;"
                                v-model.number="channelForm.configRespList[0].deductionMoney" clearable :min="0" disabled
                                :max="99999" placeholder="扣费金额 0-99999" :controls="false" /> <span
                                style="width:200px;margin-left:5px"> 元</span>
                        </el-form-item>
                        <el-form-item label="优惠权益包" prop="configRespList.0.packageCode">
                            <BlackSelect v-model:select-value="channelForm.configRespList[0].packageCode" disabled
                                style="width: 304px;" :options="listCollect.equityPackageList"></BlackSelect>
                        </el-form-item>
                        <!-- 扩展信息 -->
                        <el-form-item v-for="(domain, index) in channelForm.configRespList[0].extInfo" :key="index"
                            :label="'信息扩展' + (index + 1)">
                            <el-row style="width: 100%" justify="space-around">
                                <el-col :span="6">
                                    <el-input v-model="domain.key" placeholder="请输入value" disabled
                                        :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"></el-input>
                                </el-col>
                                <el-col :span="15">
                                    <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" disabled
                                        type="textarea" placeholder="请输入value" clearable></el-input>
                                </el-col>
                          <!--       <el-col :span="2">
                                    <el-button type="danger" style="margin-top: 12px" size="small"
                                        @click="removeDomain(domain, 1)" :icon="Minus" />
                                </el-col> -->
                            </el-row>
                        </el-form-item>

                        <!-- <el-form-item label="添加信息扩展">
                            <el-button type="primary" @click="btnAdd(1)" :icon="Plus" style="width: 100%" />
                        </el-form-item> -->
                    </template>
                    <template v-if="showModel == 2">
                        <el-divider content-position="left" v-if="channelForm.schemeType == '2'">签约（续约优惠）</el-divider>
                        <el-row>
                            <el-col :span="10">
                                <el-form-item prop="configRespList.1.annualStart" label="续约期数">
                                    <el-input-number v-model.number="channelForm.configRespList[1].annualStart" disabled
                                        clearable :min="1" :max="9998" placeholder="起始值 1-9998" :controls="false" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="configRespList.1.annualEnd" label-width="10px">
                                    <el-input-number v-model.number="channelForm.configRespList[1].annualEnd" clearable disabled
                                        :min="1" :max="9999" placeholder="结束值 1-9999" :controls="false" />
                                </el-form-item>

                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="10">
                                <el-form-item label="期数间隔" prop="configRespList.1.intervalPeriod"
                                    style="margin-right: 10px">
                                    <el-input-number v-model.number="channelForm.configRespList[1].intervalPeriod" disabled
                                        clearable :min="1" :max="127" placeholder="期数间隔" :controls="false" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item prop="periodUnit" label-width="10px">
                                    <BlackSelect style="width: 150px; margin-right:10px" disabled
                                        v-model:select-value="channelForm.configRespList[1].periodUnit" 
                                        :options="expiryPeriodType" placeholder="请选择期数单位"></BlackSelect>
                                </el-form-item>

                            </el-col>
                        </el-row>
                        <el-form-item label="扣费金额" prop="configRespList.1.deductionMoney">
                            <el-input-number v-model.number="channelForm.configRespList[1].deductionMoney" clearable disabled
                                style="width: 145px;" :precision="2" :min="0" :max="99999" placeholder="扣费金额 0-99999"
                                :controls="false" />
                            <span style="margin-left:5px"> 元</span>
                        </el-form-item>
                        <el-form-item label="优惠权益包" prop="configRespList.1.packageCode">
                            <BlackSelect v-model:select-value="channelForm.configRespList[1].packageCode" disabled
                                style="width: 304px;" :options="listCollect.equityPackageList"></BlackSelect>
                        </el-form-item>
                        <!-- 这个不用做循环 -->
                        <!-- 扩展信息 -->
                        <el-form-item v-for="(domain, index) in channelForm.configRespList[1].extInfo" :key="index"
                            :label="'信息扩展' + (index + 1)">
                            <el-row style="width: 100%" justify="space-around">
                                <el-col :span="6">
                                    <el-input v-model="domain.key" placeholder="请输入value" disabled
                                        :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"></el-input>
                                </el-col>
                                <el-col :span="15"> 
                                    <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" disabled
                                        type="textarea" placeholder="请输入value" clearable></el-input>
                                </el-col>
                             <!--    <el-col :span="2">
                                    <el-button type="danger" style="margin-top: 12px" size="small"
                                        @click="removeDomain(domain, 2)" :icon="Minus" />
                                </el-col> -->
                            </el-row>
                        </el-form-item>

                    <!--     <el-form-item label="添加信息扩展">
                            <el-button type="primary" @click="btnAdd(2)" :icon="Plus" style="width: 100%" />
                        </el-form-item> -->
                    </template>

                </el-form>
            </div>
        </template>
        <template v-slot:myFooter>
            <div class="dialog-footer">
                <el-button @click="onClose">取消</el-button>
                <el-button @click="showModel = 1" v-if="channelForm.schemeType == '2' && showModel == 2">上一步</el-button>
                <el-button type="primary" @click="onNext"
                v-if="channelForm.schemeType == '2' && showModel == 1">下一步</el-button>

             <!--  
               
          
                <el-button type="success" @click="onConfirmSimple" v-if="channelForm.schemeType == '1'"
                    :disabled="btnLoading">确定</el-button>
                <el-button type="success" @click="onConfirmComplex"
                    v-if="channelForm.schemeType == '2' && showModel == 2" :disabled="btnLoading">确定</el-button> -->
            </div>
        </template>

    </SysDialogSlot>
</template>

<style lang="scss" scoped>
.channel-form {
    height: 550px;
    overflow: auto;
}
:deep(.el-input__inner){
    text-align: left;
}
:deep(.el-radio__inner) {
    border-radius: 2px !important;
}

:deep(.el-radio__input.is-checked .el-radio__inner::after) {
    content: '';
    width: 8px;
    height: 3px;
    border: 1px solid black;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 3px;
    left: 2px;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
}
</style>
